<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/7/23
 * Time: 11:12
 */

namespace app\admin\controller\firm;
use app\common\controller\Backend;
use app\common\model\FirmUrl;

class Label extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('FirmLabel');
        $action = $this->request->action();
        if($action == 'edit' || $action == 'add'){
            $ids = $this->request->param('ids/d');
            $url_id = model('FirmLabel')->where('id',$ids)->value('url_id');
            $this->view->assign("url_id",$url_id);
            if($this->request->isPost()){
                $param = $this->request->param();
                if(!$param["row"]["url_id"]) $this->error(__('请选择URL路径'));
            }
        }
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['id', 'name'], false);
            $total = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach($list as &$item){
                $item['url_name'] = FirmUrl::where('id',$item['url_id'])->value('url_name');
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function storeSelect(){
        $keyword = $this->request->param('name');
        $where = [];
        if($this->request->request("keyValue")){
            $ids = explode(",",$this->request->request("keyValue"));
            $where['id'] = ['in',$ids];
        }
        if($keyword){
            $where['url_name'] = ['like',"%$keyword%"];
        }
        $store = model('firm_url')->where($where)->order('id desc')->field(['id', 'url_name name'])->select();
        foreach($store as $item){
            $item['name'] = $item['name']."(id: ".$item['id'].")";
        }
        return json(['list' => $store, 'total' => count($store)]);
    }
}